package com.take.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.take.common.BaseContext;
import com.take.common.R;
import com.take.entity.Dish;
import com.take.entity.Setmeal;
import com.take.entity.ShoppingCart;
import com.take.service.DishService;
import com.take.service.SetmealService;
import com.take.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车
 */
@Api(tags = "购物车模块")
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @ApiOperation("添加购物车")
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据:{}",shoppingCart);

        //设置用户id，指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Dish> queryWrapperDish = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> queryWrapperSetmeal = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        //菜品或套餐的单价
        BigDecimal singlePriceBig = new BigDecimal(0);

        if(dishId != null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
            //查菜品单价
            queryWrapperDish.eq(Dish::getId,dishId);
            Dish oneDish = dishService.getOne(queryWrapperDish);
            singlePriceBig = oneDish.getPrice();
        }else{
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
            //查套餐单价
            queryWrapperSetmeal.eq(Setmeal::getId,shoppingCart.getSetmealId());
            Setmeal oneSetmeal = setmealService.getOne(queryWrapperSetmeal);
            singlePriceBig = oneSetmeal.getPrice();
        }
        //查询菜品或套餐的价格


        //查询当前菜品或者套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart cartItem = shoppingCartService.getOne(queryWrapper);

        if(cartItem != null){
            //如果已经存在，就在原来数量基础上加1
            Integer newNumber = cartItem.getNumber()+1;
            cartItem.setNumber(newNumber);
            // 重新计算价格

            cartItem.setAmount(singlePriceBig);
            shoppingCartService.updateById(cartItem);
        }else{
            //如果不存在，则添加到购物车，数量默认就是1件
            shoppingCart.setNumber(1);
            shoppingCart.setAmount(singlePriceBig);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            cartItem = shoppingCart;
        }

        return R.success(cartItem);
    }

    /**
     * 减少菜品
     * @param shoppingCart {dishId: "1535948114657665026", setmealId: null}
     * @return
     */
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){
        // 判断是减少菜品数量？还是减少套餐数量？
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Dish> queryWrapperDish = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> queryWrapperSetmeal = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        //菜品或套餐的单价
        BigDecimal singlePriceBig = new BigDecimal(0);
        if(shoppingCart.getDishId()!=null){
            //减少菜品数量
            lqw.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
            //查菜品单价
            queryWrapperDish.eq(Dish::getId,shoppingCart.getDishId());
            Dish oneDish = dishService.getOne(queryWrapperDish);
            singlePriceBig = oneDish.getPrice();
        }else{
            //减少套餐数量
            lqw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
            //查套餐单价
            queryWrapperSetmeal.eq(Setmeal::getId,shoppingCart.getSetmealId());
            Setmeal oneSetmeal = setmealService.getOne(queryWrapperSetmeal);
            singlePriceBig = oneSetmeal.getPrice();
        }
        ShoppingCart cartItem = shoppingCartService.getOne(lqw);
        //判断如果只剩下1个，就删除掉数据库中相关记录；否则，只是减少1个数量
        int number = cartItem.getNumber();
        if (number>1) {
            number = number - 1;
            cartItem.setNumber(number);
            //价格重新计算下
            cartItem.setAmount(singlePriceBig);
            shoppingCartService.updateById(cartItem);
            return R.success("数量减少1件");
        }else{
            shoppingCartService.removeById(cartItem);
            return R.success("已从购物车中删除");
        }

    }

    /**
     * 查看购物车
     * @return
     */
    @ApiOperation("查看购物车")
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @ApiOperation("清空购物车")
    @DeleteMapping("/clean")
    public R<String> clean(){
        //SQL:delete from shopping_cart where user_id = ?

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        shoppingCartService.remove(queryWrapper);

        return R.success("清空购物车成功");
    }
}